package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Override
    public List<SkuDTO> querySkuBySpuId(Long spuId) {

        return SkuDTO.convertEntityList(this.query().eq("spu_id",spuId).list());
    }

    @Override
    public List<SkuDTO> querySkuBySpuIds(List<Long> ids) {

        return SkuDTO.convertEntityList(this.listByIds(ids));

    }

    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";

    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {

        this.executeBatch(sqlSession -> {

            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {

                // 准备参数
                Map<String,Object> param = new HashMap<>();

                param.put("id",entry.getKey());

                param.put("num",entry.getValue());

                // 编译statement,namespace.statementId
                sqlSession.update(DEDUCT_STOCK_STATEMENT,param);

            }

            // 刷新
            sqlSession.flushStatements();

        });

    }
}
